package com.yuanjin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;

import android.os.AsyncTask;

public class HttpData extends AsyncTask<String, Void, String> {
	// 通过http请求，请求方式为get方式
	private HttpClient mhttpclient;
	private HttpGet mhttpget;
	private HttpResponse mhttpresponse;
	private HttpEntity mhttpentity;
	private InputStream in;
	private String url;
	private HttpGetDataListener listener;

	public HttpData(String url, HttpGetDataListener listener) {
		this.url = url;
		this.listener = listener;
	}

	@Override
	protected String doInBackground(String... params) {
		try {
			// 实例化客户端
			mhttpclient = new DefaultHttpClient();
			mhttpget = new HttpGet(url);
			mhttpresponse = mhttpclient.execute(mhttpget);
			// 通过mhttpresponse获取实体对象
			mhttpentity = mhttpresponse.getEntity();
			// 获取数据后需要将数据转化为流文件处理
			in = mhttpentity.getContent();
			// 获取数据后通过缓冲区进行读取
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			// 获取数据
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * 获取数据后需要重写改方法，为了将数据传递给其他应用使用，可以采取回调的方式，创建一个接口HttpDataListener
	 */
	@Override
	protected void onPostExecute(String result) {
		// 接口listener通过调用getDataUrl方法将数据返回
		listener.getDataUrl(result);
		super.onPostExecute(result);
	}

}
